#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time         : 17-12-12 下午1:38
# @Author       : xiaohan
# @File         : serializers.py
# @desc         :
import re

from datetime import datetime, timedelta

from django.contrib.auth import get_user_model
from rest_framework import serializers
from rest_framework.validators import UniqueValidator

from apps.user.models import UserProfile, VerifyCode

from cadmin.settings import REGEX_MOBILE, EXPIRE_TIME

User = get_user_model()


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'


class SmsSerializer(serializers.Serializer):
    phone = serializers.CharField(max_length=11)

    def validate_phone(self, phone):
        """
        验证手机号码
        :param data:
        :return:
        """
        code = ''

        # 验证手机号码是否合法
        if not re.match(REGEX_MOBILE, phone):
            raise serializers.ValidationError({'msg': "手机号码非法"})

        # # 手机是否注册
        # if User.objects.filter(phone=phone).count():
        #     raise serializers.ValidationError({'msg': "用户已经存在"})

        # 验证码发送频率
        one_mintes_ago = datetime.now() - timedelta(hours=0, minutes=EXPIRE_TIME, seconds=0)
        ver_code = VerifyCode.objects.filter(add_time__gt=one_mintes_ago, phone=phone)
        if ver_code.count():
            ret = list(ver_code.values())[0]
            count = ret.get('count')
            if count >= 10:
                raise serializers.ValidationError({'msg': '靠靠靠,要死啊'})
            VerifyCode.objects.filter(phone=phone).update(count=count + 1)
            raise serializers.ValidationError(
                {'msg': '距离上一次发送未超过3分钟', 'code': ret.get('code')})

        return phone


class UserRegSerializer(serializers.ModelSerializer):
    code = serializers.CharField(required=True, write_only=True, max_length=4, min_length=4, label="验证码",
                                 error_messages={
                                     "blank": "请输入验证码",
                                     "required": "请输入验证码",
                                     "max_length": "验证码格式错误",
                                     "min_length": "验证码格式错误"
                                 },
                                 help_text="验证码")
    username = serializers.CharField(label="用户名", help_text="用户名", required=True, allow_blank=False,
                                     validators=[UniqueValidator(queryset=User.objects.all(), message="用户已经存在")])

    password = serializers.CharField(
        style={'input_type': 'password'}, help_text="密码", label="密码", write_only=True,
    )

    # def create(self, validated_data):
    #     user = super(UserRegSerializer, self).create(validated_data=validated_data)
    #     user.set_password(validated_data['password'])
    #     user.save()
    #     return user

    def validate_code(self, code):
        verify_records = VerifyCode.objects.filter(phone=self.initial_data['username'])
        if verify_records:
            one_mintes_ago = datetime.now() - timedelta(hours=0, minutes=EXPIRE_TIME, seconds=0)
            if one_mintes_ago > verify_records[0].add_time:
                raise serializers.ValidationError('验证码过期')

            if verify_records[0].code != code:
                raise serializers.ValidationError('验证码错误')
        else:
            raise serializers.ValidationError('验证码错误')

    # 对所有字段进行统一处理
    def validate(self, attrs):
        attrs['phone'] = attrs['username']
        del attrs['code']
        return attrs

    class Meta:
        model = User
        fields = ('username', 'phone', 'code', 'password')
